package com.steamedfish.auctioncloudprocess.config;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.steamedfish.auctioncloudprocess.feign.client.SecurityOAuth2Client;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig implements RequestInterceptor {

    @Autowired
    private RestTemplate restTemplate;



    @Override
    public void apply(RequestTemplate requestTemplate) {
        String token = getTokenFromRequest();
        requestTemplate.header("Authorization", token);
    }


    /**
     * 从请求投中获取token
     *
     * @param id
     * @return int
     */
    public String getTokenFromRequest(){
        String token = "";
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            token = request.getHeader("Authorization");
        } catch (Exception e) {

        }

        return token;
    }


    /**
     * 向安全服务中心获取token
     *
     * @param id
     * @return int
     */
    public String getTokenFromSecurity(){
        //向安全服务中心发起请求获取JWT
        String client_id = "client_1";
        String client_secret = "123456";
        String grant_type = "client_credentials";
        String redirect_uri = "http://www.baidu.com";
        String url = "http://auction-security-server-oauth/oauth/token?client_id=" + client_id +
                "&client_secret=" + client_secret +
                "&grant_type=" + grant_type +
                "&redirect_uri=" + redirect_uri;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        JSONObject object = JSONObject.parseObject(response.getBody());
        String token = (String) object.get("access_token");
        return token;
    }


    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
